import cn from 'classnames';
import React from 'react';
import { Link } from 'react-router-dom';
import Label from '@/components/Label';
import { Collapse, Loading, Tooltip } from '@knownsec/react-component';
import ForeignLinks from './foreignLinks';
import ShowTC from './other/ShowTC';
import s from './style.module.css';
import Icon from '@/assets/icon';
import { WARNING_SECURITYEVENT_MAP } from '@/common/common';
import { datetime } from '@/common/formatter';
import BreadCrumb from '@/components/BreadCrumb';
import { GetQueryString } from '@/common/constant';
import { useLocation, useHistory } from 'react-router-dom';
import { getGroupResult } from '~/API';
import { detail } from './test';
import EmptyData from '@/components/EmptyData';

const { Panel } = Collapse;

function Detail() {
  const search = useLocation().search;
  const id = GetQueryString(search, 'id');
  const tid = GetQueryString(search, 'tid');
  const type = GetQueryString(search, 'type');
  const sid = GetQueryString(search, 'sid');
  const rowSid = GetQueryString(search, 'rowSid');
  const backparam = GetQueryString(search, 'back');

  const [locData, setLocData] = React.useState();
  const [foundAt, setFoundAt] = React.useState();
  const [loading, setLoading] = React.useState(true);
  const [isEmpty,setIsEmpty] = React.useState(null);
  const arrtype = ['违规内容'];
  const getDate = async () => {
    const res = await getGroupResult({ id: rowSid,  data: { event_id: id } });
    if (res.status === 'success') {
      const data = res.data.data?.events[0]?.detail;
      const arr = ['', 'icp', 'keyword', 'domain'];
      data.links = {};
      if (Object.keys(data.links)[0]) {
        return false;
      }
      Object.keys(data.results).forEach((key) => {
        const locInfo = {};
        data.results[key].forEach((er) => {
          const type = arr[Number(er.risk_type)];
          !locInfo[type] && (locInfo[type] = []);
          locInfo[type].push(er);
        });
        data.links[key] = locInfo;
      });
      setLocData(data);
      setFoundAt(res.data.data?.events[0].updated_at);
      setLoading(false);
      codeDetails(data)
    }
  };
  const genExtra = (type) => {
    let isShow = false;
    const str = Object.keys(type)
      .map((e) => {
        return WARNING_SECURITYEVENT_MAP[e];
      })
      .join('、');
    for (let index = 0; index < arrtype.length; index++) {
      if (str.includes(arrtype[0])) {
        isShow = true;
        break;
      }
    }
    const style = { 'margin-right': '4rem' };
    return (
      <>
        <span className={s.typeSp} style={isShow ? style : {}}>
          {str}
        </span>
      </>
    );
  };
  const ShowCodeBtn = (type) => {
    let isShow = false;
    const str = Object.keys(type)
      .map((e) => {
        return WARNING_SECURITYEVENT_MAP[e];
      })
      .join('、');
    for (let index = 0; index < arrtype.length; index++) {
      if (str.includes(arrtype[0])) {
        isShow = true;
        break;
      }
    }
    if (isShow) {
      return (
        <div className={s.seeCode}>
          {
            <ShowTC info={type} foundAt={foundAt}>
              查看源码
            </ShowTC>
          }
        </div>
      );
    }
  };
  const showTable = (Data) => {
    return (
      <div className={s.CollapseBox}>
        <Collapse defaultActiveKey={['0']} className={s.collapse} expandIconPosition="right">
          {Data
            ? Object.keys(Data?.links).map((e, i) => {
                return (
                  <>
                    {ShowCodeBtn(Data?.links[e])}
                    <Panel
                      className={s.panTital}
                      forceRender={true}
                      header={
                        <span title={e}>
                          {e}
                        </span>
                      }
                      key={i}
                      extra={genExtra(Data?.links[e])}
                    >
                      <ForeignLinks info={Data ? Data.links[e] : {}} />
                    </Panel>
                  </>
                );
              })
            : null}
        </Collapse>
      </div>
    );
  };
  const codeDetails = (locData) => {
    const empty = (<EmptyData/>);
    const style = {
      background: '#fff9ee',
      borderWidth: '1px',
      borderStyle: 'solid',
      borderColor: '#fee8b6',
    };
    let str = '';
    const dom = [];
    if (!locData?.links) {
        setIsEmpty(null)
    }
    Object.values(locData.links).forEach((links) => {
      Object.values(links).forEach((val) => {
        if (!Array.isArray(val)) {
        setIsEmpty(null)
        }
        val.forEach((item) => {
          if (!item.risk_evidences) {
            return false;
          }
          item.risk_evidences.forEach((code) => {
            str = code.split(item.risk_domain);
            dom.push(
              <p className={s.codeRow}>
                {str.map((e, i) => {
                  if (i < str.length - 1) {
                    return (
                      <>
                        <span>{e}</span>
                        <span style={style}>{item.risk_domain}</span>
                      </>
                    );
                  } else {
                    return (
                      <>
                        <span>{e}</span>
                        <p>......</p>
                      </>
                    );
                  }
                })}
              </p>
            );
          });
        });
      });
    });
    if (dom[0]) {
        setIsEmpty( <div>
            {dom.map((e) => {
              return e;
            })}
          </div>)
    } else {
        setIsEmpty(null)
    }
  };
  const reArr = () => {
    let arr = [
      { link: '/', name: '监测列表' },
      { link: { pathname: '/dashboard', search: `id=${tid}&filter=${encodeURI(backparam)}` }, name: '结果详情' },
      { link: '', name: '风险外链详情', active: true },
    ];
    if (sid && sid !== 'undefined' && sid !== 'null') {
      arr = [
        { link: '/', name: '监测列表' },
        {
          link: { pathname: '/dashboard', search: `id=${tid}&sid=${sid}&type=${type}&filter=${encodeURI(backparam)}` },
          name: '结果详情',
        },
        { link: '', name: '风险外链详情', active: true },
      ];
    }
    return arr;
  };
  React.useEffect(() => {}, [locData]);
  React.useMemo(() => {
    getDate();
  }, []);
  return (
    <>
      <BreadCrumb
        arr={reArr()}
      />
      <div className={s.content}>
      <Loading show={loading} />

        <div className={s.content1}>
          <Label className={s.labelDetail}>风险外链详情</Label>
          <div className={s.content1_2h}>
            <p>
              <span className={s.titleSpan}>风险地址：</span>
            </p>
            <p className={cn(s.bord, s.redstyle)}> {locData ? locData.url || '--' : '--'}</p>
            <p className={s.l1r}>风险外链</p>
          </div>

          {showTable(locData)}
        </div>
        <div className={s.content1}>
          <div className={s.content1_2h}>
            <p className={s.l1r}>
              风险地址源码
              <span className={s.subtitle}>
                抓取时间:{(foundAt&&isEmpty) ? datetime(foundAt) || '--' : '--'}
              </span>
            </p>
          </div>
          <div className={s.showBox}>{isEmpty||<EmptyData/>}</div>
        </div>
      </div>
    </>
  );
}

export default Detail;
